package com.fdq.dianping.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.fdq.dianping.entity.Result;
import com.fdq.dianping.entity.ShopType;
import com.fdq.dianping.mapper.ShopTypeMapper;
import com.fdq.dianping.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fdq.dianping.util.Constants;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author fdq
 * @since 2024-12-29
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    StringRedisTemplate stringRedisTemplate;

    @Override
    public Result queryList() {
        //1.从redis获取
        List<String> typeList_fromRedis_String = stringRedisTemplate.opsForList().range(Constants.Shop_Type, 0, -1);
        //list<String>转list<shopType>
        List<ShopType> typeList_fromRedis = new ArrayList<>();
        //可能为空
        try{
            for (String shopTypeString: typeList_fromRedis_String) {
                typeList_fromRedis.add(JSONUtil.toBean(shopTypeString,ShopType.class));
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        if(!typeList_fromRedis.isEmpty()){
            return Result.success(typeList_fromRedis);
        }
        //redis未获取从数据库查
        List<ShopType> typeList = query().orderByAsc("sort").list();

        Iterator<ShopType> iterator = typeList.iterator();
        while (iterator.hasNext()){
            ShopType nextShopType = iterator.next();
            String shopType_json = JSONUtil.toJsonStr(nextShopType);
            //写入redis
            stringRedisTemplate.opsForList().rightPush(Constants.Shop_Type,shopType_json);
        }
        return Result.success(typeList);
    }
}
